package com.bolt.admin.module.sys.controller;


import com.bolt.admin.logging.annotation.LogAnnotation;
import com.bolt.admin.module.sys.dto.OrgDTO;
import com.bolt.admin.module.sys.dto.OrgQueryCriteria;
import com.bolt.admin.module.sys.entity.OrgEntity;
import com.bolt.admin.module.sys.service.OrgService;
import com.bolt.admin.module.sys.service.converter.OrgConverter;
import com.bolt.common.collection.CollectionUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.data.PageInfo;
import com.bolt.convention.data.ResultMessage;
import com.bolt.convention.data.Results;
import com.bolt.support.spring.jpa.specification.QueryHelp;
import com.bolt.support.ui.tree.helper.TreeRenderHelper;
import com.bolt.support.ui.tree.vo.UITreeNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "部门管理")
@RequestMapping("/api/sys/org")
public class OrgController {

    @Autowired
    private OrgService orgService;



    @ApiOperation("查询部门列表")
    @GetMapping(value = "/page")
    public ResultMessage<PageInfo<OrgDTO>> page(Pageable pageable, OrgQueryCriteria queryCriteria) {
        PageInfo<OrgEntity> pageInfo = orgService.findPage(pageable,
                (root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, queryCriteria, criteriaBuilder));
        return Results.success(pageInfo.map(K -> OrgConverter.toDTO(K)));
    }


    @GetMapping(value = "getTree")
    public ResultMessage<List<UITreeNode>> getTree(@RequestParam(name = "pid", required = false) String id, @RequestParam Map<String, String> params) {
        boolean loadAllNodes = !StrUtil.isEmpty(params.get("loadAllNodes")) && Boolean.parseBoolean(params.get("loadAllNodes"));
        List<UITreeNode> dataArray = new ArrayList<>();
        TreeRenderHelper.buildNodesTreeView(orgService, id, params, dataArray, loadAllNodes);
        return Results.success(dataArray);
    }

    @ApiOperation("查询菜单:根据ID获取同级与上级数据")
    @PostMapping("/findAll")
    public ResultMessage<List<UITreeNode>> findALl(@RequestBody List<String> ids) {
        if (CollectionUtil.isNotEmpty(ids)) {
            List<OrgEntity> menuEntities = orgService.findAll(ids);
            return Results.success(orgService.buildTree(menuEntities));
        }
        return Results.success(orgService.buildTree(orgService.findRoot()));
    }

    @ApiOperation("部门信息新增操作")
    @PostMapping
    @LogAnnotation(module = "部门管理", description = "部门信息新增操作")
    @RequiresPermissions("system:org,create")
    public ResultMessage create(@Validated @RequestBody OrgDTO orgDTO) {
        orgService.saveOrUpdate(orgDTO);
        return Results.success();
    }

    @ApiOperation("部门信息修改操作")
    @PutMapping
    @LogAnnotation(module = "部门管理", description = "部门信息修改操作")
    @RequiresPermissions("system:org,edit")
    public ResultMessage update(@Validated(OrgEntity.Update.class) @RequestBody OrgDTO orgDTO) {
        orgService.saveOrUpdate(orgDTO);
        return Results.success();
    }

    @DeleteMapping
    @ApiOperation(notes = "机构信息删除操作", httpMethod = "POST", value = "机构信息删除操作")
    @LogAnnotation(module = "部门管理", description = "机构信息删除操作")
    @RequiresPermissions("system:org,del")
    public ResultMessage doDelete(@RequestBody Set<String> ids) {
        if (orgService.verification(ids)) {
            return Results.error("500", "机构信息存在关联用户，不能删除！");
        }
        for (String id : ids) {
            if (!Objects.isNull(id)) {
                Optional<OrgEntity> optional = orgService.findOne(id);
                OrgEntity org;
                if (!optional.isPresent()) {
                    return Results.error("500", "查询删除记录的id出错！");
                } else {
                    org = optional.get();
                }
                orgService.del(org);
            } else {
                return Results.invalid("所有选取记录删除操作失败");
            }
        }
        return Results.success();

    }
}

 